package cn.itcast.zt.repository;

import cn.itcast.zt.domain.User;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * create by zhangtian on 2018/3/5
 */
@Repository
public class UserRepository {

    /**
     * 采用内存型的存储方式->Map
     */
    private final ConcurrentHashMap<Integer, User> repository = new ConcurrentHashMap<>() ;
    private final static AtomicInteger idGenerator = new AtomicInteger() ;

    /**
     * 保存用户对象
     * @param user
     * @return 如果保存成功，则返回true
     *          如果保存失败，则返回false
     */
    public boolean save(User user){
        boolean success = false ;
        Integer id = idGenerator.incrementAndGet() ;
        // 保存ID
        user.setId(id);

        return repository.put(id, user) == null ;
    }

    public Collection<User> findAllPersons() {
        return repository.values() ;
    }
}
